<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="医嘱编号">
          <el-input v-model="searchForm.orderId" placeholder="请输入医嘱编号" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="患者姓名">
          <el-input v-model="searchForm.patientName" placeholder="请输入患者姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="医嘱类型">
          <el-select v-model="searchForm.type" placeholder="请选择医嘱类型" clearable>
            <el-option label="临时医嘱" value="临时医嘱" />
            <el-option label="长期医嘱" value="长期医嘱" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="searchForm.priority" placeholder="请选择优先级" clearable>
            <el-option label="急诊" value="急诊" />
            <el-option label="加急" value="加急" />
            <el-option label="常规" value="常规" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="已开立" value="已开立" />
            <el-option label="执行中" value="执行中" />
            <el-option label="已执行" value="已执行" />
            <el-option label="已停止" value="已停止" />
          </el-select>
        </el-form-item>
        <el-form-item label="下达日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button 
            type="success" 
            v-permission="'medical_order:create'"
            @click="handleCreate"
          >
            <el-icon><Plus /></el-icon>新增医嘱
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="id"
        stripe
      >
        <el-table-column label="医嘱编号" prop="orderId" min-width="120" />
        <el-table-column label="患者姓名" min-width="100">
          <template #default="scope">
            <el-button type="text" @click="viewPatient(scope.row.patientId)">
              {{ scope.row.patientName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="下达医生" prop="doctorName" min-width="100" />
        <el-table-column label="所属科室" prop="departmentName" min-width="120" />
        <el-table-column label="医嘱类型" prop="type" width="100" />
        <el-table-column label="优先级" prop="priority" width="80">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)" size="small">
              {{ scope.row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="医嘱内容" min-width="200">
          <template #default="scope">
            <div v-for="(item, index) in scope.row.items" :key="index">
              <div class="order-item">
                <el-tag size="small" class="item-type">{{ item.type }}</el-tag>
                <span class="item-content">{{ item.content }}</span>
                <span v-if="item.frequency" class="item-frequency">({{ item.frequency }})</span>
              </div>
              <div v-if="item.note" class="item-note">备注：{{ item.note }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="下达时间" min-width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="执行人" min-width="100">
          <template #default="scope">
            {{ scope.row.execution?.executedByName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click="handleView(scope.row)"
              v-permission="'medical_order:read'"
            >
              查看
            </el-button>
            <el-button 
              v-if="scope.row.status === '已开立'"
              type="warning" 
              size="small"
              @click="handleEdit(scope.row)"
              v-permission="'medical_order:update'"
            >
              编辑
            </el-button>
            <el-dropdown v-if="scope.row.status !== '已停止' && scope.row.status !== '已执行'">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item 
                    v-if="scope.row.status === '已开立'" 
                    @click="handleExecute(scope.row)"
                    v-permission="'medical_order:execute'"
                  >
                    <el-icon><Check /></el-icon>开始执行
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="scope.row.status === '执行中'" 
                    @click="handleComplete(scope.row)"
                    v-permission="'medical_order:execute'"
                  >
                    <el-icon><Finished /></el-icon>完成执行
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="scope.row.status !== '已停止' && scope.row.status !== '已执行'" 
                    @click="handleStop(scope.row)"
                    v-permission="'medical_order:update'"
                  >
                    <el-icon><Close /></el-icon>停止医嘱
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { medicalOrderAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'

// 路由实例
const router = useRouter()

// 数据加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 日期范围
const dateRange = ref([])

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  orderId: '',
  patientName: '',
  type: '',
  priority: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    searchForm.startDate = val[0]
    searchForm.endDate = val[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
}

// 获取优先级标签类型
const getPriorityType = (priority) => {
  switch (priority) {
    case '急诊':
      return 'danger'
    case '加急':
      return 'warning'
    case '常规':
      return 'info'
    default:
      return ''
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '已开立':
      return 'warning'
    case '执行中':
      return 'primary'
    case '已执行':
      return 'success'
    case '已停止':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取医嘱列表
const getMedicalOrders = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await medicalOrderAPI.getMedicalOrders(params)
    tableData.value = res.data.orders
    total.value = res.data.total
  } catch (error) {
    console.error('获取医嘱列表失败', error)
    ElMessage.error('获取医嘱列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  getMedicalOrders()
}

// 重置搜索条件
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  searchForm.startDate = ''
  searchForm.endDate = ''
  currentPage.value = 1
  getMedicalOrders()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getMedicalOrders()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getMedicalOrders()
}

// 新增医嘱
const handleCreate = () => {
  router.push('/medical-orders/create')
}

// 查看医嘱
const handleView = (row) => {
  router.push(`/medical-orders/detail/${row.id}`)
}

// 编辑医嘱
const handleEdit = (row) => {
  router.push(`/medical-orders/edit/${row.id}`)
}

// 查看患者
const viewPatient = (patientId) => {
  router.push(`/patients/detail/${patientId}`)
}

// 开始执行医嘱
const handleExecute = (row) => {
  ElMessageBox.confirm('确认开始执行该医嘱？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await medicalOrderAPI.executeMedicalOrder(row.id, {
        executorId: localStorage.getItem('userId'),
        executorName: localStorage.getItem('userName'),
        executeTime: new Date()
      })
      ElMessage.success('医嘱已开始执行')
      getMedicalOrders()
    } catch (error) {
      console.error('执行医嘱失败', error)
      ElMessage.error(error.message || '执行医嘱失败')
    }
  }).catch(() => {})
}

// 完成执行医嘱
const handleComplete = (row) => {
  ElMessageBox.confirm('确认该医嘱已完成执行？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await medicalOrderAPI.updateMedicalOrder(row.id, { 
        status: '已执行',
        completionInfo: {
          completerId: localStorage.getItem('userId'),
          completerName: localStorage.getItem('userName'),
          completeTime: new Date()
        }
      })
      ElMessage.success('医嘱已完成执行')
      getMedicalOrders()
    } catch (error) {
      console.error('更新医嘱状态失败', error)
      ElMessage.error(error.message || '更新医嘱状态失败')
    }
  }).catch(() => {})
}

// 停止医嘱
const handleStop = (row) => {
  ElMessageBox.prompt('请输入停止原因', '停止医嘱', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '停止原因不能为空',
    type: 'warning'
  }).then(async ({ value }) => {
    try {
      await medicalOrderAPI.stopMedicalOrder(row.id, {
        reason: value,
        stopperId: localStorage.getItem('userId'),
        stopperName: localStorage.getItem('userName'),
        stopTime: new Date()
      })
      ElMessage.success('医嘱已停止')
      getMedicalOrders()
    } catch (error) {
      console.error('停止医嘱失败', error)
      ElMessage.error(error.message || '停止医嘱失败')
    }
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(() => {
  getMedicalOrders()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.item-type {
  margin-right: 8px;
}

.item-content {
  flex: 1;
}

.item-frequency {
  color: #666;
  margin-left: 8px;
}

.item-note {
  color: #666;
  font-size: 12px;
  margin-left: 50px;
  margin-bottom: 8px;
}
</style> 